<template>
    <section class="filled">
        <header :class="colorStatus">
            <span class="back iconfont icon-fanhuizuo white" v-show="chartReady" @click="jumpPage('/order')"></span>
            <div class="lh40 fs14 white">
                <span>{{this.gold?"模拟":"实盘"}}</span>
                <span class="ml5">{{this.curVariety.varietyName}} {{this.curVariety.contractsCode}}</span>
            </div>
        </header>

        <div class="chart-wrap">
            <ul class="pl10 pt5 pb5 lh25 fs14">
                <li :class="{active:curResoluTion==='1' && this.chartType===3&&!panKouShow}" @click="setChartResolution('1',3)">分时</li>
                <li :class="{active:curResoluTion==='1' && this.chartType===1&&!panKouShow}" @click="setChartResolution('1',1)">1分</li>
                <li :class="{active:curResoluTion==='3' && !panKouShow}" @click="setChartResolution('3')">3分</li>
                <li :class="{active:curResoluTion==='5' && !panKouShow}" @click="setChartResolution('5')">5分</li>
                <li class="timeToggle" @click="showTimeToggle=!showTimeToggle">
                    <span class="fs14">
                        <i v-show="curResoluTion!=='10'&&curResoluTion!=='30'&&curResoluTion!=='60'&&curResoluTion!=='D'">10分</i>
                        <i :class="{active:curResoluTion==='10'}" v-show="curResoluTion==='10'">10分</i>
                        <i :class="{active:curResoluTion==='30'}" v-show="curResoluTion==='30'">30分</i>
                        <i :class="{active:curResoluTion==='60'}" v-show="curResoluTion==='60'">1时</i>
                        <i :class="{active:curResoluTion==='D'}" v-show="curResoluTion==='D'">日K</i>
                    </span>
                    <div v-show="showTimeToggle">
                        <p @click.stop="setChartResolution('10')">10分</p>
                        <p @click.stop="setChartResolution('30')">30分</p>
                        <p @click.stop="setChartResolution('60')">1时</p>
                        <p @click.stop="setChartResolution('D')">日K</p>
                    </div>
                </li>
                <li :class="{active:studyShow}" class="iconfont icon-shuju" @click="setChartStudy"></li>
                <li :class="{active:panKouShow}" @click="panKouShow=!panKouShow">盘口</li>
            </ul>

            <!-- 盘口容器 -->
            <div v-show="panKouShow">
                <ol class="clearfix">
                    <li class="fl highestPrice">
                        <span class="ml30 fl">最高</span>
                        <em class="mr30 fr">{{curQuota.highestPrice||'···'}}</em>
                    </li>
                    <li class="fl lowestPrice">
                        <span class="ml30 fl">最低</span>
                        <em class="mr30 fr">{{curQuota.lowestPrice||'···'}}</em>
                    </li>
                    <li class="fl openPrice">
                        <span class="ml30 fl">开盘</span>
                        <em class="mr30 fr">{{curQuota.openPrice||'···'}}</em>
                    </li>
                    <li class="fl preClsPrice">
                        <span class="ml30 fl">昨收</span>
                        <em class="mr30 fr">{{curQuota.preClsPrice||'···'}}</em>
                    </li>
                    <li class="fl openInterest">
                        <span class="ml30 fl">持仓</span>
                        <em class="mr30 fr">{{curQuota.openInterest||'···'}}</em>
                    </li>
                    <li class="fl preOpenInterest">
                        <span class="ml30 fl">昨持仓</span>
                        <em class="mr30 fr">{{curQuota.preOpenInterest||'···'}}</em>
                    </li>
                    <li class="fl positionVolume">
                        <span class="ml30 fl">今结</span>
                        <em class="mr30 fr">{{curQuota.positionVolume||'···'}}</em>
                    </li>
                    <li class="fl preSetPrice">
                        <span class="ml30 fl">昨结</span>
                        <em class="mr30 fr">{{curQuota.preSetPrice||'···'}}</em>
                    </li>
                    <li class="fl volume">
                        <span class="ml30 fl">总手</span>
                        <em class="mr30 fr">{{curQuota.volume||'···'}}</em>
                    </li>
                    <li class="fl turnover">
                        <span class="ml30 fl">金额</span>
                        <em class="mr30 fr">{{curQuota.turnover||'···'}}</em>
                    </li>
                    <li class="fl upLimitPrice">
                        <span class="ml30 fl">涨停</span>
                        <em class="mr30 fr">{{curQuota.upLimitPrice||'···'}}</em>
                    </li>
                    <li class="fl downLimitPrice">
                        <span class="ml30 fl">跌停</span>
                        <em class="mr30 fr">{{curQuota.downLimitPrice||'···'}}</em>
                    </li>
                </ol>
            </div>
            <!-- 图表容器 -->
            <div v-show="!panKouShow" id="tv_chart_container2" ref="chart_container" :style="{height:chartHeight + 'px'}"></div>
        </div>
        <section class="order" v-show="chartReady">
            <!-- {{curOrder}} -->
            <div>
                <div class="wrap lh40">
                    <p class="clearfix fs14">
                        <span class="fl tl name pl10">{{curOrder.varietyName}}</span>
                        <span class="fl ml10">{{curOrder.direction==1?'买涨':'买跌'}}</span>
                        <span class="fl ml10" v-show="curOrder.orderMode==1">市</span>
                        <span class="fl ml10" v-show="curOrder.orderMode==2">高</span>
                        <span class="fl ml10" v-show="curOrder.orderMode==3">挂</span>
                        <span class="fl ml10">{{curOrder.tradeMode==0?'元':'角'}}</span>
                        <span class="fr wind" @click.stop="setStopWinLoss(curOrder)" v-show="curOrder.orderStatus==2">
                            <i class="bgred white">设置止盈止损</i>
                        </span>
                    </p>

                    <div class="list">
                        <p class="lh30 pl10 pr10">
                            <span class="clearfix wide">
                                <i class="fl green">{{curOrder.stopLossMoney|formatPoint(curOrder.marketPoint)}}(¥{{curOrder.stopLossPrice*curOrder.handsNum*curOrder.tradeRate*curOrder.ratio|formatMoney()}})</i>
                                <i class="fr mr5">止损价</i>
                            </span>
                            <span class="clearfix narrow">
                                <i class="fl ml5">{{curOrder.lastPrice|formatPoint(curOrder.marketPoint)}}</i>
                                <i class="fr">当前价</i>
                            </span>
                        </p>

                        <p class="lh30 pl10 pr10">
                            <span class="fl clearfix wide">
                                <i class="fl red">{{curOrder.stopWinMoney|formatPoint(curOrder.marketPoint)}}(¥{{curOrder.stopWinPrice*curOrder.handsNum*curOrder.tradeRate*curOrder.ratio|formatMoney()}})</i>
                                <i class="fr mr5">止盈价</i>
                            </span>
                            <span class="clearfix narrow">
                                <i class="fl ml5">{{curOrder.realAvgPrice|formatPoint(curOrder.marketPoint)}}</i>
                                <i class="fr">买入价</i>
                            </span>
                        </p>
                        <p class="lh30 pl10 pr10">
                            <span class="hand clearfix wide">
                                <i class="fl">{{curOrder.handsNum}}手</i>
                                <i class="fr mr10">交易手数</i>
                            </span>
                            <span class="clearfix narrow">
                                <i class="fl ml5">{{curOrder.openPrice|formatPoint(curOrder.marketPoint)}}</i>
                                <i class="fr">开仓价</i>
                            </span>
                        </p>
                        <p class="lh30 pl10">
                            <span class="clearfix w100" style="border-right: 0 none;">
                                <i class="fl" :class="{red:curOrder.earnMoney>=0,green:curOrder.earnMoney<0}">{{curOrder.sign}}{{curOrder.earnMoney
                                    || '0' |formatMoney()}}(￥{{curOrder.earnMoney*curOrder.ratio || '0'
                                    |formatMoney()}})</i>
                                <i class="fr mr10">当前赢利</i>
                            </span>
                        </p>
                    </div>
                    <p class="lh20 tl mt5 pl10 fontc1">下单时间 {{curOrder.buyTimeStr}}</p>
                    <!-- 显示金额等信息 -->
                    <p class="lh20 tl pl10 fontc1">{{openStatusStr}}</p>
                    <p class="lh40 action action-btn fs14 white" v-show="curOrder.orderStatus==2">
                        <span class="lh40 bgyellow ml5" @click.stop="sellBuy(curOrder)">平仓追反单</span>
                        <span class="lh40 bgred ml5 mr5" @click.stop="buy(curOrder)">追单</span>
                        <span class="lh40 bggreen mr5" @click.stop="sell(curOrder)">平仓</span>
                    </p>
                </div>
            </div>
        </section>

        <!-- 设置止盈止损 -->
        <div class="winLossWrap fs14" v-show="showSetWinLoss">
            <transition name="slide-fade">
                <div class="content bgwhite" v-show="showSetWinLoss">
                    <section>
                        <p class="lh25 mt10 pb5 clearfix pl15 pr15 line">
                            <span class="fl tl name">{{curWinLossItem.varietyName}}</span>
                            <span class="fl ml5" :class="{red:curWinLossItem.direction==1,green:curWinLossItem.direction==0}">{{curWinLossItem.direction==1?'买涨':'买跌'}}</span>
                            <span class="fl hand tr ml5">{{curWinLossItem.handsNum}}手</span>

                            <span class="fl ml5" v-show="curWinLossItem.orderMode==1">市</span>
                            <span class="fl ml5" v-show="curWinLossItem.orderMode==2">高</span>
                            <span class="fl ml5" v-show="curWinLossItem.orderMode==3">挂</span>

                            <span class="fl ml5">{{curWinLossItem.tradeMode==0?'元':'角'}}</span>
                            <span class="fr loss" :class="{red:curWinLossItem.earnMoney>=0,green:curWinLossItem.earnMoney<0}">￥{{curWinLossItem.earnMoney*curWinLossItem.ratio
                                || '0' |formatMoney()}}</span>
                        </p>

                        <p class="lh25 clearfix pl15 pr15 pt5">
                            <span class="fl">止损价
                                {{curWinLossItem.stopLossMoney}}（¥{{curWinLossItem.stopLossPrice*curWinLossItem.handsNum*curWinLossItem.tradeRate*curWinLossItem.ratio|formatMoney()}}）</span>
                            <span class="fr">买入价 {{curWinLossItem.realAvgPrice|formatPoint(curOrder.marketPoint)}}</span>
                        </p>
                        <p class="lh25 clearfix pl15 pr15 pb5 line">
                            <span class="fl">止盈价
                                {{curWinLossItem.stopWinMoney}}（¥{{curWinLossItem.stopWinPrice*curWinLossItem.handsNum*curWinLossItem.tradeRate*curWinLossItem.ratio|formatMoney()}}）</span>
                            <span class="fr">现价 {{curWinLossItem.lastPrice|formatPoint(curOrder.marketPoint)}}</span>
                        </p>
                    </section>
                    <section class="ml15 mr15 mt5">
                        <p class="lh25 tl">止损 (范围{{this.stopLossBeatRangeL}} ~ {{this.stopLossBeatRangeR}})</p>
                        <div class="lh30 clearfix set">
                            <p class="fl lh30 mt5 clearfix">
                                <span class="fl br2 iconfont icon-minus" :class="curWinLossItemStopLossBeat>this.stopLossBeatRangeL?'bgyellow':'bggray'"
                                    @click.stop="subStopLossBeat"></span>
                                <input class="fl" type="number" v-model="filterCurWinLossItemStopLossBeat" placeholder="0">
                                <span class="fl bgyellow br2 iconfont icon-plus" :class="curWinLossItemStopLossBeat<this.stopLossBeatRangeR?'bgyellow':'bggray'"
                                    @click.stop="addStopLossBeat"></span>
                            </p>
                            <strong class="fr green">¥{{this.stopLossMoney*curWinLossItem.ratio || '0' |formatMoney()}}</strong>
                        </div>
                        <p class="mt10"></p>
                        <p class="lh25 tl mt10">止盈(范围 {{this.stopWinBeatRangeL}} ~ {{this.stopWinBeatRangeR}})</p>
                        <div class="lh30 clearfix set mt5">
                            <p class="fl clearfix lh30">
                                <span class="fl bgyellow br2 iconfont icon-minus" :class="curWinLossItemStopWinBeat>this.stopWinBeatRangeL?'bgyellow':'bggray'"
                                    @click.stop="subStopWinBeat"></span>
                                <input class="fl" type="number" v-model="filterCurWinLossItemStopWinBeat" placeholder="0">
                                <span class="fl bgyellow br2 iconfont icon-plus" :class="curWinLossItemStopWinBeat<this.stopWinBeatRangeR?'bgyellow':'bggray'"
                                    @click.stop="addStopWinBeat"></span>
                            </p>
                            <strong class="fr red">¥{{this.stopWinMoney*curWinLossItem.ratio || '0' |formatMoney()}}</strong>
                        </div>
                    </section>
                    <section class="action lh40 mt20 fs14">
                        <em @click.stop="hideStopLossWin">取消</em>
                        <em class="red" @click.stop="submitSetWinLossBeat">确认</em>
                    </section>
                </div>
            </transition>
        </div>
        <!-- 追单 -->
        <section class="addOrderWrap fs14" v-show="showBuyItem">
            <transition name="slide-fade">
                <div class="content bgwhite" v-show="showBuyItem">
                    <div>
                        <p class="mt10 lh30 pl15 pr15 clearfix">
                            <span class="fl">买入类型</span>
                            <span class="fr" v-show="buyType=='add'">追单</span>
                            <span class="fr" v-show="buyType=='reverseAdd'">平仓追反单</span>
                        </p>
                        <p class="lh30 pl15 pr15 clearfix">
                            <span class="fl">商品类型</span>
                            <span class="fr">{{curBuyItem.varietyName}}</span>
                        </p>
                        <p class="lh30 pl15 pr15 clearfix">
                            <span class="fl">现价</span>
                            <span class="fr">{{curBuyItem.lastPrice}}</span>
                        </p>
                        <div class="clearfix lh30 pl15 pr15 set">
                            <strong class="fl">交易手数</strong>
                            <p class="fr lh30">
                                <span class="fl lh30 br2" @click="buyHandNumSub" :class="curBuyHand>0?'bgyellow':'bggray'">
                                    <svg class="icon fs50 fs20" aria-hidden="true">
                                        <use xlink:href="#icon-minus"></use>
                                    </svg>
                                </span>
                                <input class="fl lh30" type="number" v-model="filterCurBuyHand">
                                <span class="fl lh30 bgyellow br2" @click="buyHandNumAdd">
                                    <svg class="icon fs50 fs20" aria-hidden="true">
                                        <use xlink:href="#icon-plus"></use>
                                    </svg>
                                </span>
                            </p>
                        </div>
                    </div>
                    <section class="action lh40 mt20 fs14">
                        <em class @click.stop="hideAddBuyItem">取消</em>
                        <em @click="submitAddBuyItem">确认</em>
                    </section>
                </div>
            </transition>
        </section>
    </section>
</template>
<script>
    import { MessageBox, Toast, Indicator, Switch } from "mint-ui";
    import accounting from "accounting";

    import {
        line,
        volume
    } from "@views/chart/charting_library/config.js";

    //account的配置更改
    accounting.settings = {
        currency: {
            symbol: "", // default currency symbol is '$'
            format: "%s%v", // controls output: %s = symbol, %v = value/number (can be object: see below)
            decimal: ".", // decimal point separator
            thousand: ",", // thousands separator
            precision: 2 // decimal places
        },
        number: {
            precision: 0, // default precision on numbers is 0
            thousand: ",",
            decimal: "."
        }
    };
    import storage from "@/tools/storage.js";
    import axios from "axios";
    import "@views/chart/charting_library/jquery-1.11.2.min.js";
    import "@views/chart/charting_library/charting_library.min.js";
    import Datafeeds from "@views/chart/charting_library/datafeed.js";

    import { mapState, mapGetters, mapMutations } from "vuex";

    export default {
        name: "Chart",
        data() {
            return {
                winLossIcon: "./static/imgs/winlossicon.svg",

                //导航显示
                panKouShow: false,
                studyShow: false,
                showTimeToggle: false,
                //图表
                widget: null,
                //屏幕高度
                screenHeight: 0,
                //当前图表分辨率
                curResoluTion: "1",
                //当前图表类型
                chartType: 3,
                //quota定时器

                chartReady: false,
                curOrder: { hi: 1 },
                //设置止盈止损
                showSetWinLoss: false,
                curWinLossItem: {},
                curWinLossItemStopLossBeat: 0,
                curWinLossItemStopWinBeat: 0,
                //保存当前类型是追单 还是平仓并追单 add/ reverseAdd
                buyType: "",
                //追单
                showBuyItem: false,
                curBuyItem: { lastPrice: 0 },
                curBuyHand: 0.1
            };
        },
        mounted() {
            Indicator.open();
            //获取屏幕高度
            this.screenHeight =
                document.documentElement.clientHeight || document.body.clientHeight;

            //加载开市时间与配资
            this.getTradeTimeAndPeiZi();
            // 创建图表 先创建图表，完成后再加载订单
            this.createChart();
        },
        beforeDestroy() {
            this.quotaTimer && clearTimeout(this.quotaTimer);
            this.orderDetailTimer && clearTimeout(this.orderDetailTimer);
            window.UDFTimer && clearTimeout(window.UDFTimer);
        },
        computed: {
            ...mapState([
                "gold",
                "navBarShow",
                "curVariety",
                "userInfo",
                "curQuota",
                "tradeTime"
            ]),
            ...mapGetters(["getAllVariety", "getTradeTime"]),
            openStatusStr() {
                function formatTime(time) {
                    if (!time) return;
                    time = new Date(time);
                    var month = time.getMonth() + 1;
                    var date = time.getDate();
                    var hour = time
                        .getHours()
                        .toString()
                        .padStart(2, "0");
                    var minute = time
                        .getMinutes()
                        .toString()
                        .padStart(2, "0");
                    return month + "月" + date + "日 " + hour + ":" + minute;
                }
                formatTime(this.getTradeTime.exchangeNextTime);
                if (this.getTradeTime.exchangeStatus) {
                    return (
                        "开市中，持仓至: " + formatTime(this.getTradeTime.inventoryNextTime)
                    );
                } else {
                    return "已休市，下次交易时间: " + this.getTradeTime.nextTime;
                }
            },
            colorStatus() {
                if (this.curQuota.upDropSpeed < 0) {
                    return "bggreen";
                } else {
                    return "bgred";
                }
            },
            //当前窗口高度
            chartHeight() {
                return this.screenHeight - 360;
            },
            filterCurBuyHand: {
                get() {
                    this.curBuyHand = +this.curBuyHand.toFixed(1);
                    return this.curBuyHand;
                },
                set(hand) {
                    if (hand) {
                        hand = parseFloat(hand).toFixed(1);
                        if (hand > 0) {
                            this.curBuyHand = +hand;
                        }
                    }
                }
            },
            // 为设置止盈止损加一去过滤
            filterCurWinLossItemStopLossBeat: {
                get() {
                    // return this.curWinLossItemStopLossBeat.toFixed(
                    //     this.curVariety.marketPoint
                    // );
                    return this.curWinLossItemStopLossBeat;
                },
                set(price) {
                    price = parseFloat(price);
                    var initPrice = parseFloat(0);
                    if (price < initPrice) {
                        price = initPrice;
                    }
                    if (String(price).split(".")[1]) {
                        var length = String(price).split(".")[1].length;
                        if (length > +this.curOrder.marketPoint) {
                            return;
                        }
                    }
                    this.curWinLossItemStopLossBeat = price;
                }
            },
            filterCurWinLossItemStopWinBeat: {
                get() {
                    // return this.curWinLossItemStopWinBeat.toFixed(
                    //     this.curVariety.marketPoint
                    // );
                    return this.curWinLossItemStopWinBeat;
                },
                set(price) {
                    price = parseFloat(price);
                    var initPrice = parseFloat(0);
                    if (price < initPrice) {
                        price = initPrice;
                    }
                    if (String(price).split(".")[1]) {
                        var length = String(price).split(".")[1].length;
                        if (length > +this.curOrder.marketPoint) {
                            return;
                        }
                    }
                    this.curWinLossItemStopWinBeat = price;
                }
            },
            //设置止盈止损范围
            stopLossBeatRangeL() {
                if (this.curWinLossItem && this.curWinLossItem.direction == 0) {
                    return +(
                        this.curWinLossItem.lastPrice + this.curWinLossItem.beatFewPoints
                    ).toFixed(this.curWinLossItem.marketPoint);
                }
                if (
                    this.curWinLossItem &&
                    this.curWinLossItem.direction == 1 &&
                    this.curWinLossItem.limitStopLossMoney
                ) {
                    return this.curWinLossItem.limitStopLossMoney;
                }
            },
            stopLossBeatRangeR() {
                if (
                    this.curWinLossItem &&
                    this.curWinLossItem.direction == 0 &&
                    this.curWinLossItem.limitStopLossMoney
                ) {
                    return this.curWinLossItem.limitStopLossMoney;
                }
                if (this.curWinLossItem && this.curWinLossItem.direction == 1) {
                    return +(
                        this.curWinLossItem.lastPrice - this.curWinLossItem.beatFewPoints
                    ).toFixed(this.curWinLossItem.marketPoint);
                }
            },
            //设置止盈止损时 止损止盈金
            stopLossMoney() {
                if (this.curWinLossItem && this.curWinLossItem.direction == 0) {
                    return (
                        (this.curWinLossItem.realAvgPrice - this.curWinLossItemStopLossBeat) *
                        this.curWinLossItem.eachPointMoney *
                        this.curWinLossItem.handsNum *
                        this.curWinLossItem.tradeRate
                    );
                }
                if (this.curWinLossItem && this.curWinLossItem.direction == 1) {
                    return (
                        (this.curWinLossItemStopLossBeat - this.curWinLossItem.realAvgPrice) *
                        this.curWinLossItem.eachPointMoney *
                        this.curWinLossItem.handsNum *
                        this.curWinLossItem.tradeRate
                    );
                }
            },
            stopWinBeatRangeL() {
                if (
                    this.curWinLossItem &&
                    this.curWinLossItem.direction == 0 &&
                    this.curWinLossItem.limitStopWinMoney
                ) {
                    return this.curWinLossItem.limitStopWinMoney;
                }
                if (this.curWinLossItem && this.curWinLossItem.direction == 1) {
                    return +(
                        this.curWinLossItem.lastPrice + this.curWinLossItem.beatFewPoints
                    ).toFixed(this.curWinLossItem.marketPoint);
                }
            },
            stopWinBeatRangeR() {
                if (this.curWinLossItem && this.curWinLossItem.direction == 0) {
                    return +(
                        this.curWinLossItem.lastPrice - this.curWinLossItem.beatFewPoints
                    ).toFixed(this.curWinLossItem.marketPoint);
                }
                if (
                    this.curWinLossItem &&
                    this.curWinLossItem.direction == 1 &&
                    this.curWinLossItem.limitStopWinMoney
                ) {
                    return this.curWinLossItem.limitStopWinMoney;
                }
            },
            //设置止盈止损时 止损止盈金
            stopWinMoney() {
                if (this.curWinLossItem && this.curWinLossItem.direction == 0) {
                    return (
                        (this.curWinLossItem.realAvgPrice - this.curWinLossItemStopWinBeat) *
                        this.curWinLossItem.eachPointMoney *
                        this.curWinLossItem.handsNum *
                        this.curWinLossItem.tradeRate
                    );
                }
                if (this.curWinLossItem && this.curWinLossItem.direction == 1) {
                    return (
                        (this.curWinLossItemStopWinBeat - this.curWinLossItem.realAvgPrice) *
                        this.curWinLossItem.eachPointMoney *
                        this.curWinLossItem.handsNum *
                        this.curWinLossItem.tradeRate
                    );
                }
            }
        },
        methods: {
            ...mapMutations([
                "setGold",
                "setTradeTime",
                "setPeiZhi",
                "setCurQuota",
                "setCurVariety"
            ]),
            initVariety() {
                const varietyType = this.$route.query.varietyType;
                const batchNo = this.$route.query.batchNo;

                if (!varietyType || !batchNo) {
                    this.$router.push({
                        path: "/order"
                    });
                } else {
                    if (varietyType != this.curVariety.varietyType) {
                        this.getAllVariety.map((value, idx) => {
                            if (value.varietyType == varietyType) {
                                this.$store.commit("setCurVariety", value);
                            }
                        });
                    }
                    // 加载行情
                    this.getQuota();

                    // 请求订单
                    this.getOrder();
                }
            },
            createChart() {
                var _this = this;
                var widget = new TradingView.widget({
                    datafeed: new Datafeeds.UDFCompatibleDatafeed(
                        "//quota.zcmrr.com/quota/quota/getQuotaByRange.do",
                        this.tradeTime && this.tradeTime.status ? 1500 : 10000
                    ),
                    // library_path: "./charting_library",
                    width: "100%",
                    height: this.chartHeight,
                    interval: 1,
                    timezone: "Asia/Hong_Kong",
                    container_id: "tv_chart_container2",
                    custom_css_url: "../../charting_library/chart.css",
                    loading_screen: { backgroundColor: "#fff" },
                    locale: "zh",
                    disabled_features: [
                        "use_localstorage_for_settings",
                        "header_saveload",
                        "header_screenshot",
                        "header_settings",
                        "header_compare",
                        "header_undo_yellowo",
                        "timeframes_toolbar",
                        "timeframes_toolbar",
                        "remove_library_container_border",
                        "border_around_the_chart",
                        "display_market_status",
                        "show_logo_on_all_charts",
                        "show_chart_property_page",
                        "panel_context_menu",
                        "widget_logo",
                        "left_toolbar",
                        "header_widget",
                        "timeframes_toolbar",
                        "edit_buttons_in_legend",
                        "context_menus",
                        "control_bar",
                        "volume_force_overlay"
                    ],
                    enabled_features: [
                        "study_templates",
                        "keep_left_toolbar_visible_on_small_screens",
                        "side_toolbar_in_fullscreen_mode",
                        "property_pages"
                    ],
                    charts_storage_url: "http://saveload.tradingview.com",
                    charts_storage_api_version: "1.1",
                    user_id: "",
                    overrides: line,
                    theme: "light",
                    preset: "mobile",
                    studies_overrides: volume
                });
                widget.MAStudies = [];
                widget.selectedIntervalButton = null;
                _this.widget = widget;

                _this.chartReady = true;
                widget.onChartReady(() => {
                    _this.chartReady = true;
                    // 图表加载完成后再加载订单;
                    this.initVariety();
                });
            },
            setChartSymbol(code) {
                this.widget.chart().setSymbol(code, () => { });
            },
            setChartResolution(e, type) {
                if (e) {
                    this.curResoluTion = e;
                    this.widget.chart().setResolution(e);
                    type ? (this.chartType = type) : (this.chartType = 1);
                    this.widget.chart().setChartType(this.chartType);
                }
                this.panKouShow = false;
                this.showTimeToggle = false;
            },
            setChartStudy() {
                if (this.widget.MAStudies.length > 0) {
                    this.widget.MAStudies.forEach((value, idx, arr) => {
                        this.widget.chart().removeEntity(this.widget.MAStudies[idx]);
                    });
                    this.widget.MAStudies = [];
                    this.$set(this.widget, "MAStudies", []);
                    return;
                }
                this.widget
                    .chart()
                    .createStudy("Moving Average", !0, !1, [5, "close", 0], id => {
                        this.$set(this.widget.MAStudies, this.widget.MAStudies.length, id);
                    });
                this.widget
                    .chart()
                    .createStudy("Moving Average", !0, !1, [10, "close", 0], id => {
                        this.$set(this.widget.MAStudies, this.widget.MAStudies.length, id);
                    });
                this.widget
                    .chart()
                    .createStudy("Moving Average", !0, !1, [20, "close", 0], id => {
                        this.$set(this.widget.MAStudies, this.widget.MAStudies.length, id);
                    });
                this.widget
                    .chart()
                    .createStudy("Moving Average", !0, !1, [40, "close", 0], id => {
                        this.$set(this.widget.MAStudies, this.widget.MAStudies.length, id);
                    });
                this.panKouShow = false;
            },
            getTradeTimeAndPeiZi() {
                Indicator.open("加载订单中");
                const getTradeTime = () => {
                    return axios.get("/order/order/getTradeTime.do", {
                        params: {
                            exchangeId: this.curVariety.exchangeId,
                            varietyType: this.curVariety.varietyType,
                            _: new Date().getTime()
                        }
                    });
                };
                axios
                    .all([getTradeTime()])
                    .then(
                        axios.spread(tradeTime => {
                            tradeTime = tradeTime.data;
                            //commit交易时间
                            if (tradeTime.code == 200) {
                                this.$store.commit("setTradeTime", tradeTime.data);
                            } else {
                                MessageBox("交易时间", tradeTime.msg);
                            }
                        })
                    )
                    .then(() => {
                        Indicator.close();
                    });
            },
            removeWidget() {
                this.$refs.chart_container.innerHTML = "";

                // if (this.widget) {
                // 	this.widget.remove();
                // 	clearInterval(window.UDFTimer);//关闭数据请求
                // 	clearInterval(window.UDFTimer);//关闭数据请求
                // 	this.widget = null;
                // }

                this.widget = null;
                window.UDFTimer && clearInterval(window.UDFTimer); //关闭数据请求
            },
            //quota
            getQuota() {
                if (!this.curVariety.contractsCode) return;
                axios({
                    methods: "get",
                    url: "//quota.zcmrr.com/quota/quota/getQuotaDataAllByWeb.do",
                    params: {
                        contractsCode: this.curVariety.contractsCode,
                        _: new Date().getTime()
                    }
                })
                    .then(res => {
                        res = res.data;
                        if (res.code == 200) {
                            this.$store.commit("setCurQuota", res.data);
                            var lastPrice = { close: res.data.lastPrice };
                            window.lastPrice = res.data.lastPrice;
                            this.$set(this.curWinLossItem, "lastPrice", res.data.lastPrice);
                        } else {
                            window.lastPrice = null;
                        }
                    })
                    .then(() => {
                        //设置开闭市时间间隔
                        var step;
                        if (this.getTradeTime.exchangeStatus) {
                            step = 1000;
                        } else {
                            step = 10000;
                        }
                        this.quotaTimer = setTimeout(() => {
                            if (this.$route.path !== "/detailorder") {
                                clearTimeout(this.quotaTimer);
                            } else {
                                this.getQuota();
                            }
                        }, step);
                    })
                    .catch(() => {
                        //设置开闭市时间间隔
                        var step;
                        if (this.getTradeTime.exchangeStatus) {
                            step = 1000;
                        } else {
                            step = 10000;
                        }
                        this.quotaTimer = setTimeout(() => {
                            if (this.$route.path !== "/detailorder") {
                                clearTimeout(this.quotaTimer);
                            } else {
                                this.getQuota();
                            }
                        }, step);
                    });
            },
            getOrder() {
                const batchNo = this.$route.query.batchNo;

                axios({
                    methods: "get",
                    url: "/order/newOrder/findNewOrderList.do",
                    params: {
                        payType: this.gold ? 0 : 1,
                        batchNo //加上这个参数，只查询当前订单
                    }
                })
                    .then(res => {
                        res = res.data;
                        if (res.code == 200) {
                            if (res.data.length === 0) {
                                MessageBox.alert("订单已被平仓", "查询订单").then(action => {
                                    this.removeWidget();
                                    this.$nextTick(() => {
                                        this.$router.push({
                                            path: "/historyOrder"
                                        });
                                    });
                                });
                            } else {
                                res.data.map((value, idx) => {
                                    if (value.batchNo == batchNo) {
                                        const v = this.curQuota;
                                        const pointMoney =
                                            +value.eachPointMoney * value.beatFewPoints;
                                        if (value.direction == 1) {
                                            var money =
                                                (v.lastPrice - value.realAvgPrice) *
                                                value.eachPointMoney *
                                                value.handsNum *
                                                value.tradeRate;
                                        }
                                        if (value.direction == 0) {
                                            var money =
                                                (value.realAvgPrice - v.lastPrice) *
                                                value.eachPointMoney *
                                                value.handsNum *
                                                value.tradeRate;
                                        }

                                        value["lastPrice"] = v.lastPrice;
                                        // 追单选项的时时价写入
                                        this.$set(this.curBuyItem, "lastPrice", v.lastPrice);

                                        value["openPrice"] = v.openPrice;
                                        value["pointMoney"] = pointMoney;
                                        value["earnMoney"] = money;

                                        this.curOrder = value;
                                    }
                                });
                            }
                        } else if (res.code == 503) {
                            Toast("请先登录");
                            this.$router.push({
                                path: "/login"
                            });
                        } else {
                            MessageBox(res.msg ? res.msg : "出错");
                        }
                        // 返回订单的长度
                        return res.data.length;
                    })
                    .then(res => {
                        this.orderDetailTimer = setTimeout(() => {
                            if (this.$route.path !== "/detailorder") {
                                clearTimeout(this.orderDetailTimer);
                            } else {
                                this.getOrder();
                            }
                        }, 2000);
                    })
                    .catch(() => {
                        MessageBox("网络错误");
                    });
            },
            jumpPage(page) {
                //移除图表并回到首页
                this.removeWidget();
                this.$nextTick(() => {
                    this.$router.push({
                        path: page
                    });
                });
            },
            // 取消止盈止损
            hideStopLossWin() {
                this.initcurWinLossItem();
            },
            //控制止盈止损 - + 范围
            subStopLossBeat() {
                if (this.curWinLossItemStopLossBeat > this.stopLossBeatRangeL) {
                    this.curWinLossItemStopLossBeat -= this.curWinLossItem.beatFewPoints;
                    this.curWinLossItemStopLossBeat = +this.curWinLossItemStopLossBeat.toFixed(
                        this.curVariety.marketPoint
                    );
                }
            },
            addStopLossBeat() {
                if (this.curWinLossItemStopLossBeat < this.stopLossBeatRangeR) {
                    this.curWinLossItemStopLossBeat += this.curWinLossItem.beatFewPoints;
                    this.curWinLossItemStopLossBeat = +this.curWinLossItemStopLossBeat.toFixed(
                        this.curVariety.marketPoint
                    );
                }
            },
            subStopWinBeat() {
                if (this.curWinLossItemStopWinBeat > this.stopWinBeatRangeL) {
                    this.curWinLossItemStopWinBeat -= this.curWinLossItem.beatFewPoints;
                    this.curWinLossItemStopWinBeat = +this.curWinLossItemStopWinBeat.toFixed(
                        this.curVariety.marketPoint
                    );
                }
            },
            addStopWinBeat() {
                if (this.curWinLossItemStopWinBeat < this.stopWinBeatRangeR) {
                    this.curWinLossItemStopWinBeat += this.curWinLossItem.beatFewPoints;
                    this.curWinLossItemStopWinBeat = +this.curWinLossItemStopWinBeat.toFixed(
                        this.curVariety.marketPoint
                    );
                }
            },
            // 设置止盈止损
            setStopWinLoss(item) {
                Indicator.open("加载订单详情");
                this.curWinLossItem = item;

                this.curWinLossItemStopLossBeat = item.stopLossMoney;
                this.curWinLossItemStopWinBeat = item.stopWinMoney;

                axios({
                    methods: "post",
                    url: "/order/newOrder/findNewOrderVarietyPrice.do",
                    params: {
                        batchNo: item.batchNo,
                        payType: this.gold ? 0 : 1
                    }
                }).then(res => {
                    Indicator.close();
                    res = res.data;
                    if (res.code == 200) {
                        //修改curWinLossItem,加入 range
                        this.$set(
                            this.curWinLossItem,
                            "limitStopLossMoney",
                            res.data.limitStopLossMoney
                        );
                        this.$set(
                            this.curWinLossItem,
                            "limitStopWinMoney",
                            res.data.limitStopWinMoney
                        );

                        this.showSetWinLoss = true;
                    } else {
                        MessageBox("设置止盈止损", res.msg ? res.msg : "出错");
                    }
                });
            },
            //追单
            buy(item) {
                this.buyType = "add";
                this.curBuyItem = item;
                this.showBuyItem = true;
                this.curBuyHand = item.handsNum;
            },
            //平仓
            sell(item) {
                Indicator.open();
                axios({
                    methods: "post",
                    url: "/order/newOrder/unwindNewOrder.do",
                    params: {
                        payType: this.gold ? 0 : 1,
                        batchNo: item.batchNo,
                        unwindPrice: item.lastPrice
                    }
                }).then(res => {
                    Indicator.close();
                    res = res.data;
                    if (res.code == 200) {
                        MessageBox.alert(res.msg, "平仓").then(action => {
                            this.removeWidget();
                            this.$nextTick(() => {
                                this.$router.push({
                                    path: "/order"
                                });
                            });
                        });
                    } else {
                        Toast(res.msg);
                    }
                });
            },
            // 追单的单数调整
            buyHandNumSub() {
                if (this.curOrder.orderMode === 1) {
                    var step = 1;
                } else {
                    var step = 0.1;
                }
                if (this.curBuyHand > step) {
                    this.curBuyHand = this.curBuyHand - step;
                }
                if (step === 0.1) {
                    this.curBuyHand = +this.curBuyHand.toFixed(1);
                }
            },
            buyHandNumAdd() {
                if (this.curOrder.orderMode === 1) {
                    var step = 1;
                } else {
                    var step = 0.1;
                }
                this.curBuyHand = this.curBuyHand + step;
                if (step === 0.1) {
                    this.curBuyHand = +this.curBuyHand.toFixed(1);
                }
            },
            //平追单
            sellBuy(item) {
                this.buyType = "reverseAdd";
                this.curBuyItem = item;
                this.showBuyItem = true;
                this.curBuyHand = item.handsNum;
            },
            initcurWinLossItem() {
                this.showSetWinLoss = false;
                this.curWinLossItem = {};
                this.curWinLossItemStopLossBeat = 0;
                this.curWinLossItemStopWinBeat = 0;
            },
            hideAddBuyItem() {
                this.initBuyItem();
            },
            submitAddBuyItem() {
                if (this.buyType == "add") {
                    var tip = "追单";
                    var url = "/order/newOrder/appendNewOrder.do";
                    var params = {
                        payType: this.gold ? 0 : 1,
                        handsNum: this.curBuyHand,
                        batchNo: this.curBuyItem.batchNo,
                        orderPrice: this.curBuyItem.lastPrice
                    };
                } else if (this.buyType == "reverseAdd") {
                    var tip = "平仓反追单";
                    var url = "/order/newOrder/unwindAndReverseNewOrder.do";
                    var params = {
                        payType: this.gold ? 0 : 1,
                        handsNum: this.curBuyHand,
                        batchNo: this.curBuyItem.batchNo,
                        orderPrice: this.curBuyItem.lastPrice,
                        unwindPrice: this.curBuyItem.lastPrice
                    };
                } else {
                    MessageBox("buyType类型错误");
                    return;
                }
                Indicator.open();

                axios({
                    methods: "post",
                    url,
                    params
                })
                    .then(res => {
                        Indicator.close();
                        res = res.data;

                        MessageBox(tip, res.msg);
                        if (res.code == 200) {
                            if (this.buyType == "add") {
                                MessageBox(tip, res.msg);
                            } else if (this.buyType == "reverseAdd") {
                                MessageBox.alert(res.msg, tip).then(action => {
                                    this.removeWidget();
                                    this.$nextTick(() => {
                                        this.$router.push({
                                            path: "/order"
                                        });
                                    });
                                });
                            } else {
                                MessageBox(tip, res.msg);
                            }
                        } else {
                            MessageBox(tip, res.msg);
                        }
                    })
                    .then(() => {
                        this.initBuyItem();
                    });
            },
            //设置止盈止损
            submitSetWinLossBeat() {
                Indicator.open();
                axios({
                    methods: "post",
                    url: "/order/newOrder/updateNewOrderStopPrice.do",
                    params: {
                        payType: this.gold ? 0 : 1,
                        batchNo: this.curWinLossItem.batchNo,
                        stopLosePrice: this.curWinLossItemStopLossBeat,
                        stopWinPrice: this.curWinLossItemStopWinBeat
                    }
                })
                    .then(res => {
                        Indicator.close();
                        res = res.data;
                        MessageBox("设置止盈止损", res.msg);
                    })
                    .then(() => {
                        this.initcurWinLossItem();
                    });
            },
            //init 追单
            initBuyItem() {
                this.buyType = "";
                this.showBuyItem = false;
                this.curBuyItem = {};
            }
        },
        filters: {
            formatMoney(money) {
                if (money) {
                    return accounting.formatMoney(money);
                }
            },
            formatPoint(price, point) {
                if (price) {
                    return price.toFixed(point);
                }
            }
        }
    };
</script>
<style scoped>
    .chart-wrap ul {
        display: flex;
    }

    .chart-wrap ul li {
        background-color: #f6f6f6;
        flex: 1;
        margin-right: 5px;
        border-radius: 2px;
    }

    .chart-wrap ul li:last-child {
        margin-right: 10px;
    }

    .active {
        background-color: #f6f6f6;
        color: #ee9b2e;
    }

    .chart-wrap ul li .icon {
        vertical-align: -6px;
    }

    .gold .active {
        color: #ee9b2e;
    }

    .nav-wrap {
        background-color: #353642;
        width: 100%;
        position: fixed;
        top: 0;
        left: 0;
        z-index: 100;
    }

    .nav-wrap p span {
        height: 4px;
        width: 1rem;
        border-radius: 2px;
    }

    .nav ul li {
        width: 25%;
        text-align: center;
    }

    .br2 {
        border-radius: 2px;
    }

    .nav ul li span {
        display: inline-block;
        background-color: #4c4c57;
        width: 80%;
        border-radius: 2px;
        font-size: 14px;
        margin-top: 8px;
        line-height: 28px;
    }

    .nav ul li.select span {
        background-color: #ee9b2e;
    }

    .back {
        position: absolute;
        top: 1px;
        left: 10px;
        line-height: 40px;
        text-align: center;
        width: 30px;
        height: 40px;
    }

    .teach {
        position: absolute;
        top: 0;
        right: 10px;
        line-height: 40px;
        text-align: center;
        height: 40px;
    }

    ol {
        border-top: 1px solid #666;
    }

    ol li {
        width: 50%;
        line-height: 30px;
        font-size: 14px;
        box-sizing: border-box;
        color: #999;
        border-right: 1px solid #666;
        border-bottom: 1px solid #666;
    }

    ol li:nth-of-type(even) {
        border-right: 0 none;
    }

    ol li em,
    ol li span {
        white-space: nowrap;
    }

    .timeToggle {
        position: relative;
    }

    .timeToggle::after {
        content: "";
        width: 0;
        height: 0;
        border: 6px solid transparent;
        border-bottom-color: #feaa37;
        position: absolute;
        bottom: -5px;
        right: -6px;
        transform: rotate(135deg);
    }

    .timeToggle div {
        position: absolute;
        top: 30px;
        right: 0;
        min-width: 60px;
        background-color: #fff;
        border-radius: 2px;
        box-shadow: 0 0 4px rgba(0, 0, 0, 0.3);
        font-size: 14px;
        line-height: 30px;
        white-space: nowrap;
        z-index: 99;
    }

    .timeToggle div p {
        border-bottom: 1px solid #e2e2e2;
    }

    .timeToggle div p:last-child {
        border-bottom: 0 none;
    }

    .toggle {
        line-height: 30px;
        margin-top: 10px;
        margin-left: auto;
        margin-right: auto;
        width: 50%;
    }

    .toggle span {
        border: 1px solid #000;
        line-height: 28px;
        width: 50%;
        box-sizing: border-box;
    }

    .toggle span:nth-child(1) {
        border-right: 1px solid #000;
        border-top-left-radius: 2px;
        border-bottom-left-radius: 2px;
    }

    .toggle span:nth-child(2) {
        border-top-right-radius: 2px;
        border-bottom-right-radius: 2px;
    }

    .toggle span.select {
        color: #fff;
        border-color: #fff;
    }

    .wind i {
        display: inline-block;
        height: 24px;
        line-height: 24px;
        padding-left: 5px;
        padding-right: 5px;
        border-radius: 2px;
        margin-right: 10px;
    }

    .hold {
        border-radius: 2px;
        width: 50px;
        position: absolute;
        top: 50px;
        right: 10px;
        z-index: 99;
        color: #202734;
    }

    .yellow {
        color: #ee9b2e;
    }

    .bgyellow {
        background-color: #ef9d2e;
    }

    .list p {
        display: flex;
        border-bottom: 1px solid #e2e2e2;
        white-space: nowrap;
    }

    .list p span.wide {
        width: 65%;
    }

    .list p span.narrow {
        width: 35%;
    }

    .list p span.equal {
        width: 50%;
    }

    .list {
        border-top: 1px solid #e2e2e2;
    }

    .list p span:first-child {
        border-right: 1px solid #e2e2e2;
    }

    .winLossWrap,
    .addOrderWrap {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        width: 100%;
        height: 100%;
        z-index: 102;
        background-color: rgba(0, 0, 0, 0.5);
    }

    .winLossWrap .content,
    .addOrderWrap .content {
        position: absolute;
        width: 100%;
        bottom: 0;
        overflow: hidden;
    }

    .winLossWrap .action,
    .addOrderWrap .action {
        display: flex;
        justify-content: space-between;
        border-top: 1px solid #ddd;
    }

    .winLossWrap .action em,
    .addOrderWrap .action em {
        width: 50%;
        /*text-align: center;*/
    }

    .winLossWrap .action em:first-child,
    .addOrderWrap .action em:first-child {
        border-right: 1px solid #ddd;
    }

    .winLossWrap .set p,
    .addOrderWrap .set p {
        box-sizing: border-box;
        background-color: #fff;
        border: 1px solid #fff;
        border-radius: 2px;
        overflow: hidden;
    }

    .winLossWrap .set span,
    .addOrderWrap .set span {
        box-sizing: border-box;
        width: 30px;
        height: 30px;
        color: #fff;
    }

    .winLossWrap .set input,
    .addOrderWrap .set input {
        box-sizing: border-box;
        border: 0 none;
        line-height: 30px;
        width: 80px;
        text-align: center;
    }

    .winLossWrap .set .icon,
    .addOrderWrap .set .icon {
        margin-top: 7px;
    }

    .action-btn {
        position: fixed;
        width: 100%;
        left: 0;
        bottom: 5px;
        display: flex;
    }

    .action-btn span {
        width: 30%;
        flex: 1;
        border-radius: 4px;
    }

    .bggray {
        background-color: #aaa;
    }

    .line {
        border-bottom: 1px solid #e2e2e2;
    }

    @media screen and (min-height: 736px) {
        body {
            font-size: 12px;
        }

        body .fs14 {
            font-size: 14px;
        }

        body .fs12 {
            font-size: 12px;
        }
    }

    /*动画*/
    .slide-fade-enter-active {
        transition: all 0.2s ease;
    }

    .slide-fade-leave-active {
        transition: all 0.2s ease;
    }

    .slide-fade-enter,
    .slide-fade-leave-to

    /* .slide-fade-leave-active for below version 2.1.8 */
        {
        transform: translateY(100%);
    }
</style>